<?php

namespace App\Http\Controllers\Manage;

use App\Model\Admin;
use App\Model\Client;
use App\Model\Feedback;
use App\Model\Follow;
use App\Model\Order;
use App\Model\Product;
use App\Model\Project;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use function MongoDB\BSON\toJSON;
use Session;

class InfoController extends Controller
{
    public function infoLoginIndex()
    {
        $info = '';
        #获取客户数今日新增数
        $info['clientCount'] = Client::getAllCount();
        $info['clientTodayCount'] = Client::getTodayCount();
        #获取项目数今日新增数
        $info['projectCount'] = Project::getAllCount();
        $info['projectTodayCount'] = Project::getTodayCount();
        #获取订单数今日新增数
        $info['orderCount'] = Order::getAllCount();
        $info['orderTodayCount'] = Order::getTodayCount();

        return view('manage.info.index',['info'=>$info]);
    }

    ###销售日报报表
    public function saleDayCount(){
//        $res = $this->getUserDepartInfo("07096344529966");
        $res = $this->getDeparUser("07096344529966");
        dd($res);
        $page = Input::get('page');
        $count = Input::get('count');
        ###csv导出标识
        $csv_flag = Input::get('csv_flag',0);
        $t_time = Input::get('t_time',date("Y/m/d",time()-24*60*60).' - '.date("Y/m/d",time()-24*60*60));
        $t_time_arr = explode("-",$t_time);
        $stime = trim(str_replace("/","-",$t_time_arr[0]))." 00:00:00";
        $etime = trim(str_replace("/","-",$t_time_arr[1]))." 23:59:59";
        //TODO 查看权限问题
        $admin_id = session('user')['id'];
        $admin_info = Admin::where("id",$admin_id)->select("department","isLeader","dd_id")->first()->toArray();
        ###是领导则查看手下的所有人，否则则查看自己的
        $deps = json_decode($admin_info['department'],true);
        $dd_ids = [];
        if($admin_info['isLeader'] > 0){
            foreach ($deps as $val){
                $dd_ids[] = Admin::where("department","like","%".$val."%")->value("dd_id");
            }
        }else{
            $dd_ids[] = $admin_info['dd_id'];
        }
        ###获取规定时间内的根据记录
        $follow_list = Follow::whereBetween("create_time",[$stime,$etime])->whereIn("personnel_id",$dd_ids)->orderBy("id","desc");
        if($csv_flag > 0){
            $follow_list = $follow_list->get()->toArray();
        }else{
            $follow_list = $follow_list->paginate(10);
        }
        if(empty($page)){
            $count = Follow::whereBetween("create_time",[$stime,$etime])->whereIn("personnel_id",$dd_ids)->count();
        }
        foreach ($follow_list as $key=>&$value){
            ###创建人信息
            $op_info = Admin::where("dd_id",$value['personnel_id'])->select("isLeader","department","nickname")->first();
            $value['op_info'] = $op_info;
            ###创建人部门信息
            $op_depart_info = DB::table("department")->whereIn("id",json_decode($op_info['department'],true))->first();
            $value['op_depart_info'] = $op_depart_info;
            ###部门主管
            if($op_info['isLeader'] == 1){
                $department_admin = $op_info['nickname'];
            }else{
                $department_admin = Admin::where("department","like","%".$op_info['department']."%")->where("isLeader",1)->value("nickname");
            }
            $value['department_admin'] = $department_admin;
            $first_info = [];
            $project_info = [];
            switch ($value['category']){
                ###客户
                case 0:
                    $first_info = Client::where("id",$value['follow_id'])->select("first_name","first_phone","company","create_time")->first();
                    break;
                ###项目
                case 1:
                    $project_info = Project::where("id",$value['follow_id'])->select("id","stage","product_id","future_price","next_visit","client_id")->first();
                    ###项目状态
                    $stage = $this->stage();
                    $project_info['stage_str'] = $stage[$project_info['stage']];
                    if($project_info['product_id']){
                        $project_info['product_id_str'] = Product::whereIn("id",explode(",",$project_info['product_id']))->pluck("name")->toArray();
                    }else{
                        $project_info['product_id_str'] = [];
                    }
                    $first_info = Client::where("id",$project_info['client_id'])->select("first_name","first_phone","company","create_time")->first();
                    break;
            }
            switch ($value["form"]){
                case "0":$value["form_str"] = "上门";break;
                case "1":$value["form_str"] = "电话";break;
                case "2":$value["form_str"] = "网络";break;
            }
            $value['project_info'] = $project_info;
            $value['first_info'] = $first_info;
        }
        if($csv_flag > 0){
            ###导出CSV
            $str = "本次跟进时间,部门,部门主管,销售人员,联系人,联系方式,跟进方式,项目状态,客户名称,订购产品,预计金额,销售反馈,客户创建时间,首次跟进时间\n";
            $str = iconv('utf-8','gb2312',$str);
            foreach ($follow_list as $val){
                $department = iconv('utf-8','gb2312',$val['op_depart_info']->name); //中文转码
                $department_admin = iconv('utf-8','gb2312',$val['department_admin']);
                $op_admin = iconv('utf-8','gb2312',$val['op_info']->nickname);
                $first_name = iconv('utf-8','gb2312',$val['first_info']->first_name);
                $first_phone = iconv('utf-8','gb2312',$val['first_info']->first_phone);
                $form_str = iconv('utf-8','gb2312',$val['form_str']);
                $stage_str = iconv('utf-8','gb2312',$val['project_info']->stage_str);
                $company = iconv('utf-8','gb2312',$val['first_info']->company);
                $product_id_str = implode("/",$val['project_info']->product_id_str);
                $product_id_str = iconv('utf-8','gb2312',$product_id_str);
                $future_price = iconv('utf-8','gb2312',$val['project_info']->future_price);
                $result = iconv('utf-8','gb2312',$val['result']);
                $create_time = iconv('utf-8','gb2312',$val['first_info']->create_time);
                $next_visit = iconv('utf-8','gb2312',$val['project_info']->next_visit);
                $str .= "'".$val['create_time'].",".$department.",".$department_admin.",".$op_admin.",".$first_name.","."'".$first_phone.",".$form_str.",".$stage_str.",".$company.",".$product_id_str.","."'".$future_price.",".$result.","."'".$create_time.","."'".$next_visit."\n"; //用引文逗号分开
            }
            $filename = "saleDayInfo-".date('Ymdhis').'.csv'; //设置文件名
            $this->export_csv($filename,$str); //导出
        }else{
            return view('manage.info.saleDayCountList',[
                'count'=>$count,
                'active1' => 2,
                "follow_list"=>$follow_list,
                "t_time"=>$t_time,
            ]);
        }
    }

    ###获取个人部门信息
    public function getUserDepartInfo($dd_id){
        ###特殊组
        $all_admin_arr = ['415863491662583833'];
        if(in_array($dd_id,$all_admin_arr)){
            //特殊权限组,查看所有
            $isLeader_dep = DB::table("department")->pluck("id","name")->toArray();
            $r_arr = [];
            foreach ($isLeader_dep as $key=>$dep){
                if($dep == 1){
                    continue;
                }
                $dd_ids = Admin::where("department","like","%".$dep."%")->pluck("dd_id")->toArray();
                $r_arr[] = ['department'=>$key,"department_id"=>$dep,"dd_ids"=>$dd_ids,"is_leader"=>1];
            }
            return $r_arr;
            die();
        }
        ###获取个人部门信息
        $admin_department = Admin::where("dd_id",$dd_id)->value("department");
        $admin_department = json_decode($admin_department,true);
        $isLeader_dep = DB::table("department")->whereIn("id",$admin_department)->where("managelist","like","%".$dd_id."%")->pluck("id","name")->toArray();
        ###如果是领导,则返回其部门成员信息
        if($isLeader_dep){
            $r_arr = [];
            foreach ($isLeader_dep as $key=>$dep){
                $dd_ids = Admin::where("department","like","%".$dep."%")->pluck("dd_id")->toArray();
                $r_arr[] = ['department'=>$key,"department_id"=>$dep,"dd_ids"=>$dd_ids,"is_leader"=>1];
            }
            return $r_arr;
        }else{
            $dep_info = DB::table("department")->whereIn("id",$admin_department)->select("id","name")->first();
            return [['department'=>$dep_info->name,"department_id"=>$dep_info->id,"dd_ids"=>[$dd_id],"is_leader"=>0]];
        }
    }
    ###根据部门ID 获取下属所有部门
    public function getUserAllDep($dep_ids=[],&$department_arr=[]){
        $department_arr = array_merge($department_arr,$dep_ids);
        foreach ($dep_ids as $dep){
            $dep_arr = DB::table("department")->where("parentid",$dep)->pluck("id")->toArray();
            $this->getUserAllDep($dep_arr,$department_arr);
        }
        return array_flip(array_flip($department_arr));
    }
    ###根据DD_ID 获取用户下的所有部门和组
    public function getDeparUser($dd_id){

        ###特殊组
        $all_admin_arr = ['415863491662583833'];
        if(in_array($dd_id,$all_admin_arr)){
            //特殊权限组,查看所有
            $isLeader_dep = DB::table("department")->pluck("id","name")->toArray();
            $r_arr = [];
            foreach ($isLeader_dep as $key=>$dep){
                if($dep == 1){
                    continue;
                }
                $dd_ids = Admin::where("department","like","%".$dep."%")->pluck("dd_id")->toArray();
                $r_arr[$dep] = ['department'=>$key,"department_id"=>$dep,"dd_ids"=>$dd_ids,"is_leader"=>1];
            }
            return $r_arr;
            die();
        }
        ###正常组
        $ad_dep = Admin::where("dd_id",$dd_id)->value("department");
        $ad_dep = json_decode($ad_dep,true);
        $r_arr = [];
        foreach ($ad_dep as $dep){
            $leader_info = DB::table("department")->where("id",$dep)->first();
            if(strpos($leader_info->managelist,$dd_id) !== false){
                $all_dep = $this->getUserAllDep($ad_dep);
                foreach($all_dep as $dep_t){
                    $dd_ids = Admin::where("department","like","%".$dep_t."%")->pluck("dd_id")->toArray();
                    $name = DB::table("department")->where("id",$dep_t)->value("name");
                    $r_arr[$dep_t] = ['department'=>$name,"department_id"=>$dep_t,"dd_ids"=>$dd_ids,"is_leader"=>1];
                }
            }else{
                $r_arr[$dep] = ['department'=>$leader_info->name,"department_id"=>$dep,"dd_ids"=>[$dd_id],"is_leader"=>0];
            }
        }
        return $r_arr;


    }

    private function stage(){
        return [ // 阶段
            '0' => '初步洽谈',
            '1' => '二次回访',
            '2' => '需求确定',
            '3' => '提案/报价',
            '4' => '签单',
            '5' => '回款',
            '6' => '流单'
        ];
    }
    public function export_csv($filename,$data) {
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $data;
    }
}
